//
//  SEGBillFutureConfigViewController.m
//  SEGUhomePropertyBaseService
//
//  Created by Clavis on 2019/3/4.
//  Copyright © 2019 刘山. All rights reserved.
//

// VC
#import "SEGBillFutureConfigViewController.h"
#import "SEGBillPaymentViewController.h"
#import "SEGBillSelectRoomViewController.h"
#import "SEGBillSelectItemViewController.h"
// View
#import "SEGAddressView.h"
#import "SEGBillDiscountRuleTableViewCell.h"
// Model
#import "SEGNewBillManager.h"

@interface SEGBillFutureConfigViewController () <UITableViewDelegate, UITableViewDataSource, SEGBillSelectRoomViewDelegate>

@property (nonatomic, strong) SEGAddressView *addressView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *selectPayItemLabel;
@property (nonatomic, strong) UITextField *monthsNumberTextField;
@property (nonatomic, strong) SEGNewBillManager *manager;

@property (nonatomic, strong) NSString *houseID;
@property (nonatomic, strong) NSString *houseName;
@property (nonatomic, strong) NSString *custID;
@property (nonatomic, strong) NSString *custType;

@property (nonatomic, strong) NSMutableArray<SEGOwesDisFeeModel *> *discountArray;
@property (nonatomic, strong) NSMutableArray<SEGBillFeeItemModel *> *feeItemArray;
@property (nonatomic, strong) NSArray<SEGBillFeeItemModel *> *selectFeeItemArray;

@end

@implementation SEGBillFutureConfigViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    [self loadHouseList];
    [self addNotification];
}

- (void)setupUI {
    self.title = self.title.length>0?self.title:@"预缴";
    self.view.backgroundColor = kColor_bg;
    
    self.addressView = [[SEGAddressView alloc] init];
    self.addressView.backgroundColor = kColor_W;
    [self.addressView.titleBtn addTarget:self action:@selector(changeAddress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addressView];
    [self.addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
    }];
    
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = kColor_bg;
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.estimatedRowHeight = 44.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        [tableView registerClass:[SEGBillDiscountRuleTableViewCell class] forCellReuseIdentifier:@"SEGBillDiscountRuleTableViewCell"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.bounces = NO;
        [self.view addSubview:tableView];
        tableView;
    });
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.addressView.mas_bottom).offset(5);
    }];
    
    [self setupFooterView];
}

- (void)setupFooterView {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 200)];
    UIView *firstField = [[UIView alloc] init];
    firstField.backgroundColor = kColor_W;
    [footerView addSubview:firstField];
    [firstField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(footerView);
        make.height.mas_equalTo(44);
    }];
    UILabel *itemLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [firstField addSubview:lable];
        lable.textColor = kColor_1;
        lable.font = kFont_16;
        lable.text = @"收费项目";
        lable;
    });
    [itemLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_offset(0);
        make.width.mas_equalTo(70);
    }];
    
    self.selectPayItemLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [firstField addSubview:lable];
        lable.textColor = kColor_C;
        lable.font = kFont_16;
        lable.text = @"请选择收费项目";
        lable.textAlignment = NSTextAlignmentRight;
        lable;
    });
    [self.selectPayItemLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-31);
        make.left.equalTo(itemLabel.mas_right).offset(10);
        make.centerY.mas_offset(0);
    }];
    
    UIImageView *arrow = ({
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_more_gray")];
        [firstField addSubview:imageView];
        imageView;
    });
    [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.mas_offset(0);
    }];
    
    UIButton *selectItemButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(selectPayItemButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [firstField addSubview:button];
        button;
    });
    [selectItemButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    UIView *secondField = [[UIView alloc] init];
    secondField.backgroundColor = kColor_W;
    [footerView addSubview:secondField];
    [secondField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(firstField.mas_bottom);
        make.height.mas_equalTo(44);
    }];
    
    UILabel *numberLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [secondField addSubview:lable];
        lable.textColor = kColor_1;
        lable.font = kFont_16;
        lable.text = @"缴纳月数";
        lable;
    });
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_offset(0);
        make.width.mas_equalTo(70);
    }];
    
    self.monthsNumberTextField = ({
        UITextField *textField = [[UITextField alloc] init];
        [secondField addSubview:textField];
        textField.textColor = kColor_1;
        textField.font = kFont_16;
        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入缴纳月数" attributes:@{NSForegroundColorAttributeName : kColor_C}];
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.textAlignment = NSTextAlignmentRight;
        textField;
    });
    [self.monthsNumberTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.left.equalTo(numberLabel.mas_right).offset(10);
        make.top.bottom.mas_offset(0);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = kColor_L3;
    [footerView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(firstField.mas_bottom);
        make.left.right.equalTo(footerView);
        make.height.mas_equalTo(1);
    }];
    
    UIButton *gotoPayButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"去缴费" forState:UIControlStateNormal];
        [button setTitleColor:kColor_W forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        button.titleLabel.font = kFont_16;
        [button addTarget:self action:@selector(gotoPayButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = 2;
        button.layer.masksToBounds = YES;
        [footerView addSubview:button];
        button;
    });
    [gotoPayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(secondField.mas_bottom).offset(25);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
    }];
    
    self.tableView.tableFooterView = footerView;
}

- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)handleKeyboardWillChangeFrame:(NSNotification *)notificattion {
    NSDictionary *userInfo = [notificattion userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardHeight = keyboardRect.size.height;
    CGFloat time = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.addressView.mas_bottom).offset(5);
        if (keyboardHeight + keyboardRect.origin.y >= LYScreenHeight()) {
            make.bottom.mas_equalTo(0);
        } else {
            make.bottom.mas_equalTo(-keyboardHeight);
        }
    }];
    [UIView animateWithDuration:time animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)restUI {
    self.discountArray = [NSMutableArray array];
    self.feeItemArray = [NSMutableArray array];
    self.selectFeeItemArray = [NSArray array];
    self.monthsNumberTextField.text = nil;
    self.selectPayItemLabel.text = @"请选择收费项目";
    self.selectPayItemLabel.textColor = kColor_C;
    [self.tableView reloadData];
}

#pragma mark - Action
- (void)changeAddress:(UIButton *)sender {
    SEGBillSelectRoomViewController* VC = [[SEGBillSelectRoomViewController alloc] init];
    VC.houseId = self.houseID;
    VC.hidesBottomBarWhenPushed = YES;
    VC.delegate = self;
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)selectPayItemButtonTap:(UIButton *)sender {
    SEGBillSelectItemViewController *selectItemVC = [[SEGBillSelectItemViewController alloc] init];
    selectItemVC.feeItemArray = [self.feeItemArray mutableCopy];
    selectItemVC.selectFeeItemArray = [self.selectFeeItemArray copy];
    WeakSelf;
    selectItemVC.confirmBlock = ^(NSArray<SEGBillFeeItemModel *> * _Nonnull selectFeeItemArray) {
        weakSelf.selectFeeItemArray = selectFeeItemArray;
        NSMutableString *name = [NSMutableString string];
        NSInteger i = 0;
        for (SEGBillFeeItemModel *itemModel in selectFeeItemArray) {
            [name appendString:itemModel.feeItemTypeName];
            if (i < selectFeeItemArray.count - 1) {
                [name appendString:@"，"];
            }
            i++;
        }
        if (name.length == 0) {
            weakSelf.selectPayItemLabel.text = @"请选择收费项目";
            weakSelf.selectPayItemLabel.textColor = kColor_C;
        } else {
            weakSelf.selectPayItemLabel.text = name;
            weakSelf.selectPayItemLabel.textColor = kColor_1;
        }
    };
    [self.navigationController pushViewController:selectItemVC animated:YES];
}

- (void)gotoPayButtonTap:(UIButton *)sender {
    if (self.selectFeeItemArray.count <= 0) {
        [SEGAlertView showTmepMessageWithMessage:@"请选择收费项目"];
        return;
    }
    if (self.monthsNumberTextField.text.length == 0) {
        [SEGAlertView showTmepMessageWithMessage:@"请输入缴纳月数"];
        return;
    }
    
    NSInteger payMonths = [self.monthsNumberTextField.text integerValue];
    if (payMonths > 36) {
        [SEGAlertView showTmepMessageWithMessage:@"输入月份不能大于36个月"];
        return;
    }
    if (payMonths < 1) {
        [SEGAlertView showTmepMessageWithMessage:@"输入月份为大于0的自然数"];
        return;
    }
    
    SEGBillPaymentViewController *billPaymentVC = [[SEGBillPaymentViewController alloc] init];
    billPaymentVC.selectFeeItemArray = self.selectFeeItemArray;
    billPaymentVC.selectPayMonths = payMonths;
    billPaymentVC.houseID = self.houseID;
    billPaymentVC.houseName = self.houseName;
    billPaymentVC.custID = self.custID;
    billPaymentVC.custType = self.custType;
    [self.navigationController pushViewController:billPaymentVC animated:YES];
}

#pragma mark - handle data
- (void)loadHouseList {
    // 不再请求房屋列表，直接使用用户数据返回的数据
    SEGProfileModel *userAccount = [SEGProfileManager sharedManager].profile;
    if (userAccount.houseList.count == 0) {
        self.addressView.contentLabel.text = @"没有可用的小区！";
        return;
    }
    
    self.houseID = userAccount.houseId;
    self.houseName = userAccount.houseName;
    self.custID = userAccount.custId;
    self.custType = userAccount.defaultCustType;
    self.addressView.contentLabel.text = self.houseName;
    
    [self loadDiscountInfo];
}

- (void)loadDiscountInfo {
    NSString *communityId = kAccountCommunityID ?: @"";
    NSDictionary *params = @{@"houseId":self.houseID, @"communityId":communityId};
    WeakSelf;
    [SVProgressHUD show];
    [self.manager requestDiscountRuleWithParamsDic:params finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return;
        }
        weakSelf.discountArray = [weakSelf.manager.discountArray copy];
        weakSelf.feeItemArray = [weakSelf.manager.feeItemArray copy];
        [weakSelf.tableView reloadData];
    }];
}

#pragma mark - SEGBillSelectRoomViewDelegate - 切换小区
- (void)cell_didSelectedRoom:(SEGProfileHouselistModel *)data {
    self.houseID = data.houseId;
    self.houseName = data.fullHouseName;
    self.custID = self.custID;
    self.custType = self.custType;
    self.addressView.contentLabel.text = self.houseName;
    
    // 清空当前数据
    [self restUI];
    [self loadDiscountInfo];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.discountArray.count == 0) {
        return 0;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.discountArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGBillDiscountRuleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SEGBillDiscountRuleTableViewCell" forIndexPath:indexPath];
    SEGOwesDisFeeModel *discountModel = self.discountArray[indexPath.row];
    [cell updateTitle:discountModel.ruleName];
    WeakSelf;
    cell.joinBlock = ^{
        SEGBillPaymentViewController *billPaymentVC = [[SEGBillPaymentViewController alloc] init];
        billPaymentVC.discountModel = discountModel;
        billPaymentVC.houseID = weakSelf.houseID;
        billPaymentVC.houseName = weakSelf.houseName;
        billPaymentVC.custID = weakSelf.custID;
        billPaymentVC.custType = weakSelf.custType;
        [weakSelf.navigationController pushViewController:billPaymentVC animated:YES];
    };
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = kColor_W;
    UILabel *titleLabel = ({
        UILabel *lable = [[UILabel alloc] init];
        [header addSubview:lable];
        lable.textColor = kColor_1;
        lable.font = [UIFont boldSystemFontOfSize:15];
        lable.text = @"优惠活动";
        lable;
    });
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_offset(0);
    }];
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = kColor_W;
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, LYScreenWidth(), 5)];
    lineView.backgroundColor = kColor_bg;
    [footer addSubview:lineView];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.view endEditing:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - Getter & Setter
- (SEGNewBillManager *)manager {
    if (!_manager) {
        _manager = [[SEGNewBillManager alloc] init];
    }
    return _manager;
}

@end
